﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using DCS.ComLib.Config;
using System.IO;

///NHDuc
///Xu ly anh sau khi upload len server
namespace VietThuongLMS.Utils
{
    public class Upload
    {
        /// <summary>
        /// resize new image
        /// </summary>
        /// <param name="image"></param>
        /// <param name="maxWidth"></param>
        /// <param name="maxHeight"></param>
        /// <returns></returns>
        public static System.Drawing.Image ScaleImage(System.Drawing.Image image, int maxWidth, int maxHeight)
        {
            var ratioX = (double)maxWidth / image.Width;
            var ratioY = (double)maxHeight / image.Height;
            var ratio = Math.Min(ratioX, ratioY);

            var newWidth = (int)(image.Width * ratio);
            var newHeight = (int)(image.Height * ratio);

            var newImage = new Bitmap(newWidth, newHeight);
            Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
            return newImage;
        }

        /// <summary>
        /// Calculate image
        /// </summary>
        /// <param name="oldSize"></param>
        /// <param name="targetSize"></param>
        /// <returns></returns>
        public static Size CalculateDimensions(Size oldSize, int targetSize)
        {
            Size newSize = new Size();
            // neu kich thuoc can dinh lon hon kich thuot that (so sanh chieu rong)
            if (targetSize < oldSize.Width)
            {
                //hinh lon
                if (oldSize.Width > oldSize.Height)
                {
                    //hinh ngang
                    newSize.Width = targetSize;
                    newSize.Height = targetSize * oldSize.Height / oldSize.Width;
                }
                else
                {
                    //hinh du'ng
                    newSize.Height = targetSize;
                    newSize.Width = targetSize * oldSize.Width / oldSize.Height;
                }
            }
            else
            {
                //neu hinh nho hon kich thuoc quy dinh giu nguyen hinh
                newSize = oldSize;
            }
            return newSize;
        }

        /// <summary>
        /// create new image file with size (maxWidth, maxHeight) and save to Dest
        /// </summary>
        /// <param name="image"></param>
        /// <param name="maxWidth"></param>
        /// <param name="maxHeight"></param>
        /// <param name="Dest"></param>
        public static void CreateNewImageFile(System.Drawing.Image image, int maxWidth, int maxHeight, string Dest)
        {
            var newImage = ScaleImage(image, maxWidth, maxHeight);
            newImage.Save(Dest);
        }

        /// <summary>
        /// Resize image
        /// </summary>
        /// <param name="inputStream"></param>
        /// <param name="targetSize"></param>
        /// <param name="pathName"></param>
        public static void ResizeImageFile(Stream inputStream, int targetSize, string pathName)
        {
            using (System.Drawing.Image oldImage = System.Drawing.Image.FromStream(inputStream))
            {
                Size newSize = CalculateDimensions(oldImage.Size, targetSize);
                using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format24bppRgb))
                {
                    //newImage.SetResolution(72, 72);
                    using (Graphics canvas = Graphics.FromImage(newImage))
                    {
                        canvas.Clear(Color.White);
                        canvas.SmoothingMode = SmoothingMode.AntiAlias;
                        canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
                        canvas.DrawImage(oldImage, new Rectangle(new Point(0, 0), newSize));
                        newImage.Save(pathName, ImageFormat.Jpeg);//MapPath                  
                    }
                }
            }
        }
        static public System.Drawing.Image ResizeBitmap(System.Drawing.Image b, int nWidth, int nHeight)
        {
            Bitmap result = new Bitmap(nWidth, nHeight);
            using (Graphics g = Graphics.FromImage((System.Drawing.Image)result))
                g.DrawImage(b, 0, 0, nWidth, nHeight);
            return result;
        }
        /// <summary>
        /// update image file to destPath with width, height
        /// </summary>
        /// <param name="file"></param>
        /// <param name="targetSize"></param>    
        /// <param name="destPath"></param>
        /// <returns>new file path</returns> 
        public static string UpdateImageWithSize(HttpPostedFileBase file, int targetSize, string destPath)
        {
            int nFileLen = file.ContentLength;
            if (nFileLen == 0)
            {
                return string.Empty;
            }

            string strExtLimited = ConfigReader.ReadString("styleImage", ".bmp, .gif, .png, .jpg, .jpeg");
            string strExt = System.IO.Path.GetExtension(file.FileName).ToLower();

            if (strExtLimited.IndexOf(strExt) < 0)
            {
                return string.Empty;
            }

            int file_append = 0;
            string sFilename = System.IO.Path.GetFileName(file.FileName);
            string sSavePath;

            while (System.IO.File.Exists(destPath + sFilename))//MapPath
            {
                file_append++;
                sFilename = System.IO.Path.GetFileNameWithoutExtension(file.FileName) + file_append.ToString() + strExt;
            }

            //hFilename.Value = sFilename;
            sSavePath = destPath + sFilename;

            //if (!strExt.Trim('.').Equals("gif"))
            //    ResizeImageFile(file.InputStream, targetSize, sSavePath);
            //else
                file.SaveAs(sSavePath);

            return sFilename;
        }
    }
}